const crypto = require('crypto')

/** *
 * 生成签名
 * @param data
 * @returns {*}
 */
export function getSign(data) {
  var params = obj2Array(data)
  var sequenceParams = params.sort()
  var paramStr = sequenceParams.join('_')
  var uriAndParam = paramStr + '_' + "3213123dasda13123543fdfdas"
  var encodeUri = encodeURIComponent(uriAndParam)
  // console.warn('encodeUri:' + encodeUri)
  return secretAlgorithm(encodeUri)
}

/**
 * 加密算法
 * @param algorithm
 * @param param
 */
var secretAlgorithm = function(param) {
  var algorithmFunc = crypto.createHash('md5')
  algorithmFunc.update(param)
  return algorithmFunc.digest('hex')
}

/**
 * 对象转换为 [key0=value0[,key1=value1]]
 * @param reqBody
 * @returns {Array}
 */
function obj2Array(reqBody) {
  var params = []
  for (var key in reqBody) {
    if (reqBody[key] === undefined) {
      continue
    }
    if (reqBody[key] === null) {
      params.push(key + '=')
      continue
    }
    params.push(key + '=' + reqBody[key])
  }
  return params
}
